package net.rrkk.photoman.service;

import net.rrkk.photoman.entity.Photo;
import net.rrkk.photoman.repository.PhotoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Service
public class PhotoServiceImpl implements PhotoService {
    
    @Autowired
    private PhotoRepository photoRepository;
    
    @Value("${photo.storage.path:/photo-data}")
    private String storagePath;
    
    @Override
    public Photo createPhoto(MultipartFile file, Long categoryId, String title, String description, Boolean isPublic) {
        if (file == null || file.isEmpty()) {
            throw new RuntimeException("文件不能为空");
        }
        
        try {
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = getFileExtension(originalFilename);
            String uniqueFilename = UUID.randomUUID().toString() + "." + fileExtension;
            
            // 根据分类ID创建目录结构
            String categoryPath = categoryId != null ? categoryId.toString() : "uncategorized";
            Path uploadPath = Paths.get(storagePath, "categories", categoryPath);
            
            // 创建目录（如果不存在）
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            
            // 保存文件
            Path filePath = uploadPath.resolve(uniqueFilename);
            file.transferTo(filePath);
            
            // 获取图片信息
            BufferedImage image = ImageIO.read(filePath.toFile());
            long fileSize = Files.size(filePath);
            
            // 创建Photo实体
            Photo photo = new Photo();
            photo.setCategoryId(categoryId);
            photo.setTitle(title != null && !title.isEmpty() ? title : originalFilename);
            photo.setDescription(description);
            photo.setFilePath(filePath.toString());
            photo.setFileName(uniqueFilename);
            photo.setFileExtension(fileExtension);
            photo.setFileSize(fileSize);
            photo.setWidth(image != null ? image.getWidth() : 0);
            photo.setHeight(image != null ? image.getHeight() : 0);
            photo.setMimeType(file.getContentType());
            photo.setIsPublic(isPublic != null ? isPublic : Boolean.TRUE);
            photo.setCreatedAt(LocalDateTime.now());
            photo.setUpdatedAt(LocalDateTime.now());
            
            // 保存到数据库
            return photoRepository.save(photo);
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        }
    }
    
    @Override
    public Optional<Photo> getPhotoById(Long id) {
        return photoRepository.findById(id);
    }
    
    @Override
    public List<Photo> getAllPhotos() {
        return photoRepository.findAll();
    }
    
    @Override
    public List<Photo> getPhotosByCategoryId(Long categoryId) {
        return photoRepository.findByCategoryId(categoryId);
    }
    
    @Override
    public List<Photo> searchPhotosByTitle(String title) {
        return photoRepository.findByTitleContaining(title);
    }
    
    @Override
    public List<Photo> getPhotosByFileExtension(String fileExtension) {
        return photoRepository.findByFileExtension(fileExtension);
    }
    
    @Override
    public List<Photo> getPublicPhotos() {
        return photoRepository.findByIsPublicTrue();
    }
    
    @Override
    public List<Photo> getPrivatePhotos() {
        return photoRepository.findByIsPublicFalse();
    }
    
    @Override
    public Photo updatePhoto(Long id, Long categoryId, String title, String description, Boolean isPublic) {
        Optional<Photo> optionalPhoto = photoRepository.findById(id);
        if (optionalPhoto.isPresent()) {
            Photo photo = optionalPhoto.get();
            photo.setCategoryId(categoryId);
            photo.setTitle(title);
            photo.setDescription(description);
            photo.setIsPublic(isPublic);
            photo.setUpdatedAt(LocalDateTime.now());
            
            return photoRepository.save(photo);
        }
        return null;
    }
    
    @Override
    public void deletePhoto(Long id) {
        Optional<Photo> optionalPhoto = photoRepository.findById(id);
        if (optionalPhoto.isPresent()) {
            Photo photo = optionalPhoto.get();
            
            // 删除文件系统中的文件
            try {
                Path filePath = Paths.get(photo.getFilePath());
                if (Files.exists(filePath)) {
                    Files.delete(filePath);
                }
            } catch (IOException e) {
                // 记录日志，但不中断删除操作
                e.printStackTrace();
            }
            
            // 删除数据库记录
            photoRepository.deleteById(id);
        }
    }
    
    private String getFileExtension(String filename) {
        if (filename == null || filename.lastIndexOf(".") == -1) {
            return "";
        }
        return filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
    }
}